var lunboImgesUrl = "";
var noticeData;
var chooseUserList = [];

init()

function init() {
    queryProjectList();
}

function initProject(pageIndex,projectId) {
    $.ajax({
        url: prefixUrl + "project/queryList",
        type: "post",
        data: JSON.stringify({projectId:projectId,pageIndex:pageIndex}),
        contentType: "application/json;",
        success: function (data) {
            var projectHtml = "";
            var list = data.data.rows;
            for(var i=0; i<list.length; i++){
                projectHtml = projectHtml
                    +'<option style="text-align: center;" value="'
                    +list[i].projectId
                    +'">'
                    +list[i].projectName
                    +'</option>';
            }
            $("#projectList").html(projectHtml);
            if(projectId != null){
                $("#projectLists").val(projectId);
                queryProUserList(projectId);
            }
        }
    })
}

function queryProjectList(pageIndex) {
    $.ajax({
        url: prefixUrl + "project/queryList",
        type: "post",
        data: JSON.stringify({pageIndex:pageIndex}),
        contentType: "application/json;",
        success: function (data) {
            var projectHtml = "";
            var list = data.data.rows;
            for(var i=0; i<list.length; i++){
                projectHtml = projectHtml
                    +'<option style="text-align: center;" value="'
                    +list[i].projectId
                    +'">'
                    +list[i].projectName
                    +'</option>';
            }
            $("#projectLists").html(projectHtml);
            queryLieratureList(0);
        }
    })
}

$("#projectList").change(function () {
    queryProUserList($("#projectList").val(),1);
})

function queryProUserList(projectId,type) {
    $.ajax({
        url :   prefixUrl + "user/getProUserList",
        type:   "post",
        data:JSON.stringify({
            projectId:projectId
        }),
        contentType:"application/json;",
        success:function(data){
            goToLogin(data);
            /*var list = data.data;
            var readUserHtml  = '';
            for(var i=0; i<list.length; i++){
                readUserHtml = userHtml
                    +'<input id="'
                    +list[i].userId
                    +'" name="user" class="iptradio" type="checkbox" value="'
                    +list[i].userId + "," + list[i].userName
                    +'"">'
                    + list[i].userName;
            }
            $("#readUsers").html(userHtml);*/
            /*if(type != 1){
                //复选框回显
                setUserListCheck(noticeData.userList);
            }*/
            setUserListCheck(noticeData.userList);
        }
    });
}

function queryLieratureList(pageIndex) {
    if(pageIndex == null){
        pageIndex = 0;
    }
    $.ajax({
        url: prefixUrl + "notice/getallnoticeinfo",
        type: "post",
        data: JSON.stringify({projectId:$("#projectLists").val(),noticeTitle:$("#name").val(),pageIndex:pageIndex}),
        contentType: "application/json;",
        success: function (data) {
            goToLogin(data)
            var commonHtml = '<thead>'
                +'<tr>'
                +'<th>序号</th>'
                +'<th>公告标题</th>'
                +'<th>公告备注</th>'
                +'<th>创建时间</th>'
                +'<th>未读人数</th>'
                +'<th>操作</th>'
                +'</tr>'
                +'</thead>'
                +'<tbody>';
            var list = data.data.rows;
            for(var i=0; i<list.length; i++){
                var desc = list[i].noticeContent;if(desc.length > 30){ desc =  desc.substr(0,29) + "..."}
                var numberHtml = '';
                if(list[i].notReadNumber > 0){
                    numberHtml = '<span style="color: red;">' + list[i].notReadNumber + "人" + '</span>';
                }else{
                    numberHtml = '<span style="color: green;">' + list[i].notReadNumber + "人" + '</span>';
                }
                commonHtml = commonHtml
                    +'<tr>'
                    +'<td>' + (parseInt(i) + 1) + '</td>'
                    +'<td>'
                    +list[i].noticeTitle
                    +'</td>'
                    +'<td>'
                    +desc
                    +'</td>'
                    +'<td>'
                    +new Date(list[i].oprDate).toLocaleDateString()
                    +'</td>'
                    +'<td>'
                    +numberHtml
                    +'</td>'
                commonHtml = commonHtml
                    +'<td>'
                    +'<button type="button" class="btn btn-info mar-r-5" data-toggle="modal" data-target="#exampleModal" data-whatever="@mdo" onclick=queryLiteratureDetail("'
                    + list[i].noticeId
                    +'")><i class="glyphicon glyphicon-search"></i></button>'
                    +'<button type="button" class="btn btn-info" onclick=deleteLiterature("'
                    +list[i].noticeId
                    +'")><i class="fa fa-bitbucket-square"></i></button>'
                    +'</td>'
                    +'</tr>';
            }
            commonHtml = commonHtml + +'</tbody>';
            $("#literatureTable").html(commonHtml);

            var total = data.data.total;
            var remainder = total%20;
            var allNumber = 0;
            if(remainder > 0){
                allNumber = parseInt(total/20) + 1;
            }else{
                allNumber = parseInt(total/20);
            }
            var number = 1;
            var numberHtml = '<li><a onclick=queryLieratureList('+ "0" +')>«</a></li>';
            for(var i=0; i<allNumber; i++){
                var id = "query-" + i;
                if(i == 0){
                    numberHtml = numberHtml
                        +'<li id="'+ id + '" name="queryList" class="active"><a onclick=queryLieratureList('+ i +')>' + number + '</a></li>';
                }else{
                    numberHtml = numberHtml
                        +'<li id="'+ id + '" name="queryList"><a onclick=queryLieratureList('+ i +')>' + number + '</a></li>';
                }
                number++;
            }
            numberHtml = numberHtml + '<li><a onclick=queryLieratureList('+ (allNumber-1) +')>»</a></li>';
            $("#queryList").html(numberHtml);
        }
    })
}

function queryLiteratureDetail(id){
    $.ajax({
        url: prefixUrl + "notice/getnotice",
        type: "post",
        data: JSON.stringify({noticeId: id}),
        contentType: "application/json;",
        success: function (data) {
            noticeData = data.data;
            var detail = data.data;

            initProject(0,$("#projectLists").val());
            $("#noticeTitle").val(detail.noticeTitle);
            $("#noticeContent").val(detail.noticeContent);
            //轮播图回显
            if(detail.fileUrl !=null && detail.fileUrl != ""){
                getLunBo(detail.fileUrl);
            }else{
                getLunBo("");
            }
        }
    })
}

function setUserListCheck(userList) {
    var readUserHtml  = '';
    var notReadUserHtml  = '';
    for(var i=0; i<userList.length; i++){
        if(userList[i].state == 1){
            readUserHtml += '<span>' + userList[i].userName + '  </span>&nbsp;&nbsp;';
        }else{
            notReadUserHtml += '<span>' + userList[i].userName + '  </span>&nbsp;&nbsp;';;
        }
    }
    $("#readUsers").html(readUserHtml);
    $("#notReadUsers").html(notReadUserHtml);

    for(var i=0; i<userList.length; i++){
        var userId = userList[i].userId;
        var userName = userList[i].userName;
        var data = userId + "," + userName;
        var obj = document.getElementsByName("user");
        for(k in obj){
            var value = obj[k].value;
            if(value == data){
                $("input[id=" + userId +"]").prop("checked","true");
            }
        }
    }

}

function updateLiterature() {
    if($("#noticeTitle").val() == null ||　$("#noticeTitle").val() == ""){
        alert("标题不可为空");
        return;
    }
    getUserList();
    if(chooseUserList == null || chooseUserList == ""){
        alert("人员不可为空");
        return;
    }
    if($("#noticeContent").val() == null ||　$("#noticeContent").val() == ""){
        alert("内容不可为空");
        return;
    }
    var data = {
        noticeId : noticeData.noticeId,
        noticeTitle : $("#noticeTitle").val(),
        noticeContent : $("#noticeContent").val(),
        fileUrl : lunboImgesUrl,
        projectId:$("#projectList").val(),
        userList:chooseUserList
    };
    $.ajax({
        url: prefixUrl + "notice/updatenotice",
        type: "post",
        data: JSON.stringify(data),
        contentType: "application/json;",
        success: function (data) {
            alert(data.msg);
            modalDisplay();
            queryLieratureList(0)
        }
    })
}

function deleteLiterature(id) {
    if(confirm("确定要进行删除嘛?")){
        $.ajax({
            url: prefixUrl + "notice/deletenotice",
            type: "post",
            data: JSON.stringify({noticeId:id}),
            contentType: "application/json;",
            success: function (data) {
                alert(data.msg);
                queryLieratureList(0)
            }
        })
    }
}

function getLunBo(lunboImgUrl){
    lunboImgesUrl = lunboImgUrl;

    var lunboImgList = lunboImgUrl.split(",");

    lunboHtml = "";
    for(var i=0; i<lunboImgList.length-1; i++){
        var imgUrl = "";
        if(lunboImgList[i] != null && lunboImgList[i].indexOf("/") != -1){
            imgUrl = lunboImgList[i].split("/");
            imgUrl = imgUrl[imgUrl.length-1];
        }
        lunboHtml = lunboHtml
            +'<section class="up-section fl">'
            +'<span class="up-span"></span>'
            +'<img class="up-img" src="'
            +lunboImgList[i]
            +'">'
            +'<p class="img-name-p">'
            +imgUrl
            +'</p><input id="taglocation" name="taglocation" value="" type="hidden">'
            +'<input id="tags" name="tags" value="" type="hidden">'
            +'</section>';
    }
    $("#lunbo").html(lunboHtml);

    addFileChange();
}

function addFileChange() {
    var delParent;
    var imagesUrl;
    var defaults = {
        fileType         : ["jpg","png","bmp","jpeg"],   // 上传文件的类型
        fileSize         : 1024 * 1024 * 10                  // 上传文件的大小 10M
    };
    /*点击图片的文本框*/
    $(".file").change(function(){
        var idFile = $(this).attr("id");
        var file = document.getElementById(idFile);
        var imgContainer = $(this).parents(".z_photo"); //存放图片的父亲元素
        var fileList = file.files; //获取的图片文件
        var input = $(this).parent();//文本框的父亲元素
        var imgArr = [];
        //遍历得到的图片文件
        var numUp = imgContainer.find(".up-section").length;
        var totalNum = numUp + fileList.length;  //总的数量
        if(fileList.length > 5 || totalNum > 5 ){
            alert("上传图片数目不可以超过5个，请重新选择");  //一次选择上传超过5个 或者是已经上传和这次上传的到的总数也不可以超过5个
        }
        else if(numUp < 5){
            fileList = validateUp(fileList);
            for(var i = 0;i<fileList.length;i++){
                var imgUrl = window.URL.createObjectURL(fileList[i]);
                imgArr.push(imgUrl);
                var $section = $("<section class='up-section fl loading'>");
                imgContainer.prepend($section);
                var $span = $("<span class='up-span'>");
                $span.appendTo($section);

                var $img0 = $("<img class='close-upimg'>").on("click",function(event){
                    event.preventDefault();
                    event.stopPropagation();
                    $(".works-mask").show();
                    delParent = $(this).parent();
                });
                $img0.attr("src","img/a7.png").appendTo($section);
                var $img = $("<img class='up-img up-opcity'>");
                $img.attr("src",imgArr[i]);
                $img.appendTo($section);
                var $p = $("<p class='img-name-p'>");
                $p.html(fileList[i].name).appendTo($section);
                var $input = $("<input id='taglocation' name='taglocation' value='' type='hidden'>");
                $input.appendTo($section);
                var $input2 = $("<input id='tags' name='tags' value='' type='hidden'/>");
                $input2.appendTo($section);

            }
        }
        setTimeout(function(){
            $(".up-section").removeClass("loading");
            $(".up-img").removeClass("up-opcity");
        },450);
        numUp = imgContainer.find(".up-section").length;
        if(numUp >= 5){
            $(this).parent().hide();
        }
    });



    $(".z_photo").delegate(".close-upimg","click",function(){
        $(".works-mask").show();
        delParent = $(this).parent();
    });

    $(".wsdel-ok").click(function(){
        $(".works-mask").hide();
        var numUp = delParent.siblings().length;
        if(numUp < 6){
            delParent.parent().find(".z_file").show();
        }
        var imgName = delParent[0].textContent;
        var lunboImageList = lunboImgesUrl.split(",");
        imageUrls = "";
        if(lunboImageList.length > 0){
            for(var i=0; i<lunboImageList.length; i++){
                console.log(imgName);
                var lunbo = lunboImageList[i];
                if(lunbo != "" && lunbo.indexOf(imgName) == -1){
                    imageUrls = imageUrls + lunbo + ",";
                }
            }
        }
        lunboImgesUrl = imageUrls;
        delParent.remove();
    });

    $(".wsdel-no").click(function(){
        $(".works-mask").hide();
    });

    function validateUp(files){
        var arrFiles = [];//替换的文件数组
        for(var i = 0, file; file = files[i]; i++){
            //获取文件上传的后缀名
            var newStr = file.name.split("").reverse().join("");
            if(newStr.split(".")[0] != null){
                var type = newStr.split(".")[0].split("").reverse().join("");
                if(jQuery.inArray(type, defaults.fileType) > -1){
                    // 类型符合，可以上传
                    if (file.size >= defaults.fileSize) {
                        alert(file.size);
                        alert('您这个"'+ file.name +'"文件大小过大');
                    } else {
                        // 在这里需要判断当前所有文件中
                        var formData = new FormData();
                        formData.append('file', file);
                        saveLunBoPic(formData);
                        arrFiles.push(file);
                    }
                }else{
                    alert('您这个"'+ file.name +'"上传类型不符合');
                }
            }else{
                alert('您这个"'+ file.name +'"没有类型, 无法识别');
            }
        }
        return arrFiles;
    }
}

function getUserList(){
    var obj = document.getElementsByName("user");
    var i = 0;
    for(k in obj){
        if(obj[k].checked){
            var user = obj[k].value.split(",");
            var userInfo = {
                userId : user[0],
                userName : user[1]
            }
            chooseUserList[i] = userInfo;
            i++;
        }
    }
}